﻿<template>
  <el-dialog :title = 'dialogTitle' :visible.sync = 'dialogFormVisible' width = '80%' class = 'main_dialog md_dialog' @close = "closeDialog"
  :close-on-click-modal = 'false' :close-on-press-escape = 'false'>
    <el-form :model = "ruleForm" ref = "ruleForm" :label-width = 'labelWidth' :rules =  'rules' v-loading = 'dialogLoading'>
      <div class = 'formDialog_content'>
        <el-form-item label = "分隔符：" v-if = '!hadUploadContent'>
          <el-input v-model = 'ruleForm.split_char' placeholder = '请输入分隔符'></el-input>
        </el-form-item>
        <el-form-item label = "换行符：" v-if = '!hadUploadContent'>
          <el-input v-model = 'ruleForm.line_char' placeholder = '请输入换行符'></el-input>
        </el-form-item>
        <el-form-item label = "导入内容：" prop = 'dataContent' v-if = '!hadUploadContent'>
          <el-input type = 'textarea' v-model = 'ruleForm.dataContent' placeholder = '请粘贴需要导入的数据,默认操作是将excel中的数据粘贴到记事本再重记事本粘贴到此'></el-input>
        </el-form-item>
        <el-form-item label = "栏位对应表：" v-if = 'hadUploadContent'>
          <!-- 上传的excel中栏位与元数据中的栏位的对应关系 -->
          <div class = 'page_tableContent' style = 'minHeight:80px'>
            <div class="addColumn">
              <p @click = "addColumn"><i class="iconfont icon-add"></i>新增对应表</p>
            </div>
            <el-table :data = "ruleForm.columnsTable" style = "width:100%" empty-text = "暂无数据，请立即添加" border stripe class = 'editTable'>
              <el-table-column align = "center" label = "导入数据栏位" show-overflow-tooltip>
                <template slot-scope="scope">
                  <el-form-item :prop = "'columnsTable[' + scope.$index + '].excelName'" :rules = "rules.excelName">
                    <el-select v-model = 'scope.row.excelName' placeholder = '请选择导入数据栏位' clearable filterable :default-first-option = 'true'>
                      <el-option v-for = '(item, index) in totalColumns' :key = 'index' :label = 'item.text' :value = 'item.indexName'></el-option>
                    </el-select>
                  </el-form-item>
                </template>
              </el-table-column>
              <el-table-column align = "center" label = "元数据栏位" show-overflow-tooltip>
                <template slot-scope="scope">
                  <el-form-item  :prop = "'columnsTable[' + scope.$index + '].metaName'" :rules = "rules.metaName">
                    <el-select v-model = 'scope.row.metaName' placeholder = '请选择元数据栏位' clearable filterable :default-first-option = 'true'>
                      <el-option v-for = '(item, index) in tableColumn' :key = 'index' :label = 'item.text' :value = 'item.indexName'></el-option>
                    </el-select>
                  </el-form-item>
                </template>
              </el-table-column>
              <el-table-column align="center" label="操作" width="30">
                <template slot-scope="scope">
                  <el-button type="text" size="mini" @click = "handleColumnRemove(scope.$index)" title = '移除'>
                    <i class="iconfont icon-shanchu"></i>
                  </el-button>
                </template>
              </el-table-column>
            </el-table>
          </div>
          <!-- 固定值对应表---为元数据中的固定栏位添加固定的值 -->
          <div class = 'page_tableContent' style = 'minHeight:80px'>
            <div class="addColumn">
              <p @click = "addColumnData"><i class="iconfont icon-add"></i>新增固定值对应表</p>
            </div>
            <el-table :data = "ruleForm.columnsDataTable" style = "width:100%" empty-text = "暂无数据，请立即添加" border stripe class = 'editTable'>
              <el-table-column align = "center" label = "指定栏位的值" show-overflow-tooltip>
                <template slot-scope="scope">
                  <el-form-item :prop = "'columnsDataTable[' + scope.$index + '].columnsData'" :rules = "rules.columnsData">
                    <el-input v-model = 'scope.row.columnsData' placeholder = '请选择值'></el-input>
                  </el-form-item>
                </template>
              </el-table-column>
              <el-table-column align = "center" label = "元数据栏位" show-overflow-tooltip>
                <template slot-scope="scope">
                  <el-form-item  :prop = "'columnsDataTable[' + scope.$index + '].columnsName'" :rules = "rules.columnsName">
                    <el-select v-model = 'scope.row.columnsName' placeholder = '请选择元数据栏位' clearable filterable :default-first-option = 'true'>
                      <el-option v-for = '(item, index) in tableColumn' :key = 'index' :label = 'item.text' :value = 'item.indexName'></el-option>
                    </el-select>
                  </el-form-item>
                </template>
              </el-table-column>
              <el-table-column align="center" label="操作" width="30">
                <template slot-scope="scope">
                  <el-button type="text" size="mini" @click = "handleColumnDataRemove(scope.$index)" title = '移除'>
                    <i class="iconfont icon-shanchu"></i>
                  </el-button>
                </template>
              </el-table-column>
            </el-table>
          </div>
        </el-form-item>
      </div>
      <el-form-item class = 'form_noLeftMargin'>
        <el-button type = "info" @click = "resetForm ('ruleForm')">取 消</el-button>
        <el-button type = "primary" @click = "submitForm ('ruleForm')">确 定</el-button>
      </el-form-item>
    </el-form>
  </el-dialog>
</template>

<script>
export default {
  props: ['showDialog', 'metauid', 'tableColumn'],
  data () {
    return {
      dialogTitle: '批量导入元数据',
      dialogFormVisible: false,
      labelWidth: '100px',
      dialogLoading: false,
      // 表单部分
      ruleForm: {
        dataContent: '',
        split_char: '',
        line_char: '',
        columnsTable: [], // excel和元数据的栏位对应关系
        columnsDataTable: [] // 指定的元数据的栏位的值
      },
      // 表单规则部分
      rules: {
        dataContent: [
          {required: true, message: '导入的数据内容不可为空', trigger: 'blur'}
        ],
        excelName: [
          {required: true, message: '导入的数据的栏位不可为空', trigger: 'change'}
        ],
        metaName: [
          {required: true, message: '元数据的栏位不可为空', trigger: 'change'}
        ],
        columnsData: [
          {required: true, message: '元数据的栏位的值不能为空', trigger: 'change'}
        ],
        columnsName: [
          {required: true, message: '元数据的栏位不可为空', trigger: 'change'}
        ]
      },
      hadUploadContent: false,
      totalColumns: [],
      totalData: []
    }
  },
  methods: {
    // 初始化表单时
    initDialog () {
      this.ruleForm.dataContent = ''
      this.ruleForm.split_char = '	'
      this.ruleForm.line_char = ''
      this.hadUploadContent = false
      this.totalColumns = []
      this.totalData = []
      this.ruleForm.columnsTable = []
      this.ruleForm.columnsDataTable = []
    },
    // 新增栏位--excel和元数据栏位对应表
    addColumn () {
      this.ruleForm.columnsTable.push({
        excelName: '',
        metaName: ''
      })
    },
    // 移除栏位--excel和元数据栏位对应表
    handleColumnRemove (index) {
      this.$confirm('确定要移除该记录么?', '提示', {
        confirmButtonText: '确定',
        cancelButtonClass: 'el-button--info',
        cancelButtonText: '取消'
      }).then(() => {
        this.ruleForm.columnsTable.splice(index, 1)
        this.$message({
          message: '移除成功',
          type: 'success'
        })
      }).catch(() => {})
    },
    // 新增栏位--设置元数据栏位固定值的表
    addColumnData () {
      this.ruleForm.columnsDataTable.push({
        columnsData: '',
        columnsName: ''
      })
    },
    // 移除栏位--设置元数据栏位固定值的表
    handleColumnDataRemove (index) {
      this.$confirm('确定要移除该记录么?', '提示', {
        confirmButtonText: '确定',
        cancelButtonClass: 'el-button--info',
        cancelButtonText: '取消'
      }).then(() => {
        this.ruleForm.columnsDataTable.splice(index, 1)
        this.$message({
          message: '移除成功',
          type: 'success'
        })
      }).catch(() => {})
    },
    // 提交导入的excel中的内容,并获取到所有的数据以及相关的栏位信息
    getColumns () {
      this.$patch('/metadataset/split_data', {
        split_char: this.ruleForm.split_char,
        line_char: this.ruleForm.line_char,
        data_txt: this.ruleForm.dataContent
      }).then((data) => {
        let dataResult = data.data.result
        if (dataResult.code === 'success') {
          this.hadUploadContent = true
          if (dataResult.columns.length && dataResult.data.length) {
            for (let i = 0; i < dataResult.columns.length; i++) {
              let objExam = {
                indexName: dataResult.columns[i],
                text: dataResult.data[0][dataResult.columns[i]]
              }
              this.$set(this.totalColumns, this.totalColumns.length, objExam)
            }
          }
          this.totalData = dataResult.data
          this.$message({
            message: '数据导入成功,请选择对应的栏位表',
            type: 'success',
            duration: 3000
          })
        } else {
          this.$message({
            message: dataResult.msg,
            type: 'warning'
          })
        }
        this.dialogLoading = false
      }).catch((error) => {
        this.$message({
          message: error,
          type: 'error'
        })
        this.dialogLoading = false
      })
    },
    getData () {
      let data = []
      if (!this.ruleForm.columnsTable.length) {
        this.$message({
          message: '请选择导入数据和元数据的栏位对应关系',
          type: 'warning',
          duration: 3000
        })
        return
      }
      if (!this.totalData.length) {
        this.$message({
          message: '没有获取到相应的数据',
          type: 'warning',
          duration: 3000
        })
        return
      }
      this.dialogLoading = true
      this.totalData.forEach((item, index) => {
        // 第一行是excel的栏位
        if (index > 0) {
          let objExam = {}
          // excel和元数据的栏位的对应关系
          for (let i = 0; i < this.ruleForm.columnsTable.length; i++) {
            objExam[this.ruleForm.columnsTable[i]['metaName']] = item[this.ruleForm.columnsTable[i]['excelName']]
          }
          // 为元数据的栏位设置固定的值
          for (let i = 0; i < this.ruleForm.columnsDataTable.length; i++) {
            objExam[this.ruleForm.columnsDataTable[i]['columnsName']] = this.ruleForm.columnsDataTable[i]['columnsData']
          }
          data.push(objExam)
        }
      })
      this.addMethod(data)
    },
    // 新增的方法
    addMethod (data) {
      this.$post('/metadataset', {
        id: this.metauid,
        data: data
      }).then(data => {
        if (data.data.result.code === 'success') {
          this.$message({
            message: '操作成功',
            type: 'success',
            duration: 3000
          })
          this.$emit('operationSuccess')
        } else if (data.data.result.code === 'failed') {
          this.$message({
            message: data.data.result.msg,
            type: 'error'
          })
        }
        this.dialogLoading = false
      }).catch(error => {
        console.log(error)
        this.dialogLoading = false
      })
    },
    // 点击弹窗的取消按钮
    resetForm (forms) {
      this.$refs[forms].clearValidate()
      this.$emit('operationReset')
    },
    closeDialog () {
      this.$refs.ruleForm.clearValidate()
      this.$emit('operationReset')
    },
    // 点击弹窗的确定按钮
    submitForm (forms) {
      this.$nextTick(() => {
        this.$refs[forms].validate((valid) => {
          if (valid) {
            this.dialogLoading = true
            if (this.hadUploadContent) {
              this.getData()
            } else {
              this.getColumns()
            }
          } else {
            return false
          }
        })
      })
    }
  },
  watch: {
    showDialog: {
      handler: function (val, oldVal) {
        this.dialogFormVisible = val
        if (val) {
          this.initDialog()
        }
      },
      deep: true
    }
  }
}
</script>

<style lang = "scss" scoped>
  .formDialog_content {
    max-height: 660px;
    overflow-x: hidden;
    margin-bottom: 10px;
  }
  @media(max-height: 760px) {
    .formDialog_content {
      max-height: 430px;
      overflow-x: hidden;
      margin-bottom: 10px;
    }
  }
</style>
